<?php

namespace App\Providers;

use App\Http\Library\IDCard;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // 扩展数据库方法
        Builder::macro('findInSet', function ($field, $value) {
            return $this->whereRaw("FIND_IN_SET(?, {$field})", $value);
        });
        Builder::macro('orderByWith', function ($relation, $column, $direction = 'asc'): Builder {
            if (is_string($relation)) {
                $relation = $this->getRelationWithoutConstraints($relation);
            }
            return $this->orderBy(
                $relation->getRelationExistenceQuery(
                    $relation->getRelated()->newQueryWithoutRelationships(),
                    $this,
                    $column
                ),
                $direction
            );
        });
        //验证手机号
        Validator::extend('mobile', function ($attribute, $value, $parameters, $validator) {
            $pattern = '/^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/';
            $res = preg_match($pattern, $value);
             return $res>0;
         });
        Validator::replacer('mobile', function ($message, $attribute, $rule, $parameters) {
            return $message;
        });

        //验证身份证号
        Validator::extend('idcard', function ($attribute, $value, $parameters, $validator) {
            return IDCard::validateIDCard($value);
        });
        Validator::replacer('idcard', function ($message, $attribute, $rule, $parameters) {
            return $message;
        });
    }


}
